#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/11
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from json import dumps
from flask import jsonify, session
from flasky.common import AxiosMessage, PermissionsModule
from flasky.model import Site, Place, User, Rule


class AxiosManager(AxiosMessage):
    # 接口消息管理器
    def __init__(self) -> None:
        super().__init__()
        self.vehicles = {'Car': '私家車','Moto': '電單車', 'Truck': '貨車', 'Custom':'定制'}
        self.modes = {'Monthly': '月租','Hourly': '時租', 'Test': '測試'}

    def setting_page_data(self):
        """
        设置页面数据
        """
        column_name = Site.columns_name()
        proofs = {'LicensePlate': '車牌識別','Card':'IC卡', 'Ticket':'時租票'}
        r = Site.query.first()
        site_info = r.to_dict()
        site_info['Vehicle'] = r.to_list("Vehicle")
        site_info['Mode'] = r.to_list("Mode")
        site_info['Proof'] = r.to_list("Proof")
        return {
            "ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), 
            "SiteInfo": site_info, "SiteInfoJSON": dumps(site_info,ensure_ascii=False),
            "Modes":self.modes, "Proofs":proofs, "Vehicles":self.vehicles}

    def parking_place_page_data(self):
        """
        车位管理页面数据
        """
        filters = session.get("PlaceFilter")
        if not filters:
            filters = dict.fromkeys(("Vehicle","Mode"))
        column_name = Place.columns_name()
        rows = Place.query.all()
        return {
            "ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), "Modes":self.modes, 
            "Vehicles":self.vehicles, 'TableDatas': rows, "FiltersJSON": dumps(filters,ensure_ascii=False)
        }

    def cashers_page_data(self):
        """
        收费员管理
        """
        column_name = User.columns_name()
        conditions = session.get("CasherFilter")
        if not conditions:
            conditions = dict.fromkeys(("Cashier","LoginName","UserName"))
        filters_data = conditions.copy()
        conditions["RoleID"] = PermissionsModule.user
        conditions["Delete"] = False
        filters = User.generate_filters(**conditions)
        rows = User.query.filter(*filters).all()
        return {
            "ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), "Modes":self.modes, 
            "Vehicles":self.vehicles, 'TableDatas': rows, "FiltersJSON": dumps(filters_data,ensure_ascii=False)
        }

    def rule_page_data(self):
        """
        收费规则
        """
        column_name = Rule.columns_name()
        conditions = session.get("RuleFilter")
        if not conditions:
            conditions = dict.fromkeys(("Vehicle","Price"))
        filters_data = conditions.copy()
        filters = Rule.generate_filters(**conditions)
        rows = Rule.query.filter(*filters).all()
        weekdays = {
            "1": "星期一","2":"星期二","3":"星期三","4": "星期四","5":"星期五","6":"星期六","7":"星期天",
        }
        return {
            "ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), "Modes":self.modes, 
            "Vehicles":self.vehicles, 'TableDatas': rows, "FiltersJSON": dumps(filters_data,ensure_ascii=False),
            "Weekdays":weekdays,
        }

    def __reset_filter(self, view):
        """
        清除筛选
        """
        if view == "places":
            filters = session.get("PlaceFilter")
            if filters:
                del session["PlaceFilter"]
            return "OK"

    def __set_filter(self, view, data):
        """
        设置查询条件
        """
        if view == "places":
            session['PlaceFilter'] = data
            return self.success("數據查詢中，請稍候...")

    def __delete_data(self, view, data):
        """
        删除数据
        """
        if view == "places":
            if Place.delete_data(**data):
                return self.success("車位刪除成功！")
            return self.warning("車位刪除失敗！")

    def __add_data(self, view, data):
        """
        新增数据
        """
        if view == "places":
            ret = Place.check_exists(**data)
            if not ret:
                if Place.add_data(**data):
                    return self.success("新增車位成功！")
                else:
                    return self.warning("新增車位失敗！")
            else:
                return self.warning("車位已存在！")

    def __update_data(self, view, data):
        """
        更新数据
        """
        if view == "setting":
            if Site.modify_data(**data):
                return self.success("更新車場設置成功！")
            return self.warning("車場設置更新失敗！")
        elif view == "places":
            if Place.modify_data(**data):
                return self.success("車位更新成功！")
            return self.warning("車位更新失敗！")

    def __get_data(self, view, condition):
        """
        选择数据
        """
        if view == "places":
            r = Place.query.filter_by(PlaceID=condition).first()
            return jsonify(**r.to_dict())

    def messages(self, **kwargs):
        """
        分析消息
        """
        view = kwargs.get("View")
        for k, v in kwargs.items():
            if k == "Update":
                return self.__update_data(view, v)
            elif k == "Add":
                return self.__add_data(view, v)
            elif k == "Delete":
                return self.__delete_data(view, v)
            elif k == "SetFilter":
                return self.__set_filter(view, v)
            elif k == "ResetFilter":
                return self.__reset_filter(view)
            elif k == "GetData":
                return self.__get_data(view, v)

